
function [phy5] = portSort5VWQtr(phy, P, Ret)

% PORTSORT10VW: Sort 5 value-weighted portfolios
% 
% INPUT:
%   phy: N by T matrix of sorting variable
%   P:   N by T matrix of firm market capitalization
%   Ret: N by T matrix of individual firm returns

% OUTPUT:
%   phy5: 
% 
% � Xiaoji lin and Lu Zhang 2012

% warning off

% Initializing
[N, T]  = size(Ret);
pointer = round([1; N*.20; N*.40; N*.60; N*.80; N]);  % pointers used in sorting

[N T]  = size(Ret);
T      = floor(T/4)*4;
P      = P(:,1:T);        
phy    = phy(:,1:T);     
Ret    = Ret(:,1:T);

% further initializing
lag   = 0;
phy5   = zeros([5 T - lag]);    % 5 portfolio returns formed on phy

% construct 5 portfolio returns
for t = lag + 1 : T
    % sorting and rebalancing every quarter
    
         phyvec  = phy(:, t);
         IndStru = phy5Sorting(phyvec, pointer);
        % construct equal-weighted phy10 portfolio excess returns 
         tSpan            = t : t;         % using quarterly returns
         [phy5(:, tSpan - lag)] = p5Constr(IndStru, tSpan, P, Ret);
        

end


%------------------------------subfunction declaration-----------------------------
% 
function IndStru = phy5Sorting(svec, pointer);

% phy5SORTING:
%
% sort 5 portfolios based on physical investment
% OUTPUT:
%   IndStru : structural cell (matrix of matrices of difference lengths)
% 
% � Xiaoji lin and Lu Zhang 2012

% Initializing
IndStru  = struct('idp1', [], 'idp2', [], 'idp3', [], 'idp4', [], 'idp5',[]);
% phyiscal investment sort
[ssize, sInd] = sort(svec);     clear ssize
ids1    = sInd(pointer(1)     : pointer(2));
ids2    = sInd(pointer(2) + 1 : pointer(3));
ids3    = sInd(pointer(3) + 1 : pointer(4));
ids4    = sInd(pointer(4) + 1 : pointer(5));
ids5    = sInd(pointer(5) + 1 : pointer(6));     clear sInd

% take index to form 5 portfolios
for i = 1 : 5
    eval(['IndStru.idp' num2str(i) '=ids' num2str(i) ';' ]);
end

%---------------------------------------------------------------------------
% 
function [p5]   = p5Constr(IndStru, tSpan, P, Ret);

% p5Constr:
%   construct 5 portfolios using structural cell index across the time range in tSpan
%
% OUTPUT:
%   p5 : 5 by length(tSpan) portfolio returns
% 
% � Xiaoji lin and Lu Zhang 2012

[N, T]  = size(Ret);
p5 = zeros([5 length(tSpan)]);

for i = 1 : 5
   
        % value-weighted returns
         eval(['p5(' num2str(i) ', :) = sum(P(IndStru.idp' num2str(i) ', tSpan).*Ret(IndStru.idp' num2str(i) ', tSpan)) ./sum(P(IndStru.idp' ...
            num2str(i) ', tSpan));']);
       
        % equal-weighted returns
        % eval(['p10(' num2str(i) ', :) = mean(Ret(IndStru.idp' num2str(i) ', tSpan));']);
  
end

